<template>
  <view :class="[{'is-template-3': isTemplate3}]">
    <view class="_header-top" :style="{'position': isDrawer ? 'sticky' : 'static','box-shadow': (isSticky && !isDrawer) ? '0px 4px 12px rgba(133, 148, 162, 0.25)' : '','top': !isDrawer ? navigatorHeight + 42 +'px' : '-1px'}">
      <view class="selected-sku-box">
        <view :class="['_lf', {small: isDrawer}]" @click="previewImage">
          <x-image v-if="thumbImg" :src="formatOss(thumbImg)" />
          <view class="_icon-zoom-in">
            <x-icon name="icon-062" size="36" color="#FFFFFF"/>
          </view>
        </view>
        <view class="_rt">
          <view class="_price">
            <template v-if="crossedPrice">
              <view class="original" v-if="isTemplate3">¥{{ skuOriginalPrice }}</view>
              <x-price v-else :price="skuOriginalPrice" :Price1Size="36" :Price2Size="36" />
            </template>
            <view class="_coupon-price">
              <text class="_coupon-after">实付价¥</text>
              <view v-if="crossedPrice">
                <x-count-to :start-val='skuOriginalPrice' :end-val='payPrice' :decimals='2' />
              </view>
              <view v-else>
                {{ payPrice }}
              </view>
              <text v-if="!skuPrice || !addressInfo.userProvince" class="_coupon-after">起</text>
            </view>
          </view>
          <view v-if="!isTemplate3 && [2, 3].includes(skuMode) && currentSku" class="_text">
            已选：
            <text class="_tagselect" v-if="currentCombo">
              {{ currentCombo.comboName }}
            </text>
            <text class="_tagselect" v-for="item in currentSku.attr" :key="item.value">
              <text>{{ item.value }}</text>
            </text>
          </view>
        </view>
      </view>

      <view v-if="isTemplate3" class="address-box section" @click="onAddress">
        <view class="address-content">
          <view class="address-icon">
            <x-image src="/assets/images/icon-location.png" />
          </view>
          <view v-if="addressInfo.userPhone" class="address-detail">
            <view class="user-info">
              <view class="user-name">{{ addressInfo.userName }}</view>
              <view class="user-mobile">{{ addressInfo.userPhone }}</view>
            </view>
            <view class="address">
              {{ addressInfo.addressInfo }}{{ addressInfo.userAddress }}
            </view>
          </view>
          <text class="fill-tips" v-else>请填写收货地址</text>
        </view>
        <x-icon name="icon-017" size="28" color="#999999"/>
      </view>
    </view>
    <view v-if="showAnimateBanner" class="animate-image-body">
      <view :class="animateBannerClassName">
        <view class="_lf">
          <view class="_content">
            <view v-if="limitedTimeOffer" class="_t1">恭喜您，获得今日最佳优惠</view>
            <view v-else class="_t1">恭喜您，获得优惠</view>
            <view class="_t2">现在下单，立减<text>{{ formatNumber(limitedTimeOffer || orderInfo.couponAmount) }}元</text></view>
          </view>
        </view>
        <view class="_rt">
          <p-countdown />
        </view>
      </view>
    </view>
    <view class="p-set-order section no-padding-right no-padding-left">
      <!-- 服务 -->
      <p-server v-if="!isDrawer && servicePromise && safeguardList.length" :serve-list="safeguardList" />
      <view class="_scroll">
        <view class="x-product-sku">
          <view v-if="skuMode === 3" class="_sku _combo">
            <view class="_dl">
              <view class="_dt">套餐</view>
              <view class="_dd">
                <view
                  v-for="item in comboSkuInfo"
                  :key="item.id"
                  :class="{'is-active': selectedCombo === item.id}"
                  class="_li"
                  @click="handleChangeCombo(item)"
                >
                  {{ item.comboName }}
                </view>
              </view>
              <view v-if="currentCombo && currentCombo.comboSellingPoint" class="_desc">{{ currentCombo.comboSellingPoint }}</view>
            </view>
          </view>
          <view v-if="productSkuInfo" class="_sku">
            <p-sku :list.sync="productSkuInfo" @change="handleChangeSku" />
          </view>
        </view>
        <view class="_num">
          <view class="_lf">数量</view>
          <view class="_rt">
            <view class="_jian">
              <x-button @click="handleReduceCount" :disabledType="1" :disabled="productCount <= 1" priority="secondary-secondary" size="medium" styles="border: none !important;background: #F2F3F5;padding: 0">
                <text style="font-size: 28px;line-height: 28px;">-</text>
              </x-button>
            </view>
            <view class="_num">
              <x-input placeholder=" " disabled :value.sync="productCount" type="text" size="small" textAlign="center" background="#F2F3F5" />
            </view>
            <view class="_jian">
              <x-button @click="handleAddCount" priority="secondary-secondary" size="medium" styles="border: none !important;background: #F2F3F5;padding: 0">
                <text style="font-size: 28px;line-height: 28px;">+</text>
              </x-button>
            </view>
          </view>
        </view>

        <view class="remark-box" v-if="isTemplate3">
          <view class="label">买家留言</view>
          <view class="input">
            <x-input size="mini" :value.sync="addressInfo.userMessage" placeholder="选填：对快递等的特殊要求"/>
          </view>
        </view>
      </view>
    </view>

    <view v-if="!isTemplate3" class="p-address">
      <view class="_title">
        <view class="_lf">收货地址</view>
        <!--#ifdef MP-WEIXIN-->
        <view class="_rt" @click="onAddress" v-if="isShowGetAddress">
          <view class="_use-WeiXin">
            <x-icon style="margin-right: 4px;" name="icon-030" size="30" color="#07C160"/>
            使用微信收货地址
          </view>
          <x-icon name="icon-017" size="28" color="#999999"/>
        </view>
        <!--#endif-->
      </view>
      <view class="cell-group">
        <view class="cell">
          <view class="_lf-title">收货人</view>
          <view class="flex1 bold">
            <x-input size="mini" fontSize="30" maxlength="10" :value.sync="addressInfo.userName" placeholder="收货人姓名"/>
          </view>
        </view>
        <view class="cell">
          <view class="_lf-title">手机号</view>
          <view class="flex1 bold">
            <x-input size="mini" fontSize="30" maxlength="11" :value.sync="addressInfo.userPhone" type="number" placeholder="收货人11位手机号" @blur="handleBlurPhone" />
          </view>
        </view>
        <view class="cell">
          <view class="_lf-title">所在地区</view>
          <picker style="flex: 1" mode="region" :value="addressInfo.multiIndex" @change="multiChange">
            <view class="adress-info bold" :style="{'color' : addressInfo.addressInfo ? '#323233' : '#999999'}">
              {{addressInfo.addressInfo || '省/市/区'}}
            </view>
          </picker>
          <view class="_rt">
            <x-icon name="icon-017" size="28" color="#999999"/>
          </view>
        </view>
        <view class="cell">
          <view class="_lf-title">详细地址</view>
          <view class="flex1 bold">
            <x-input size="mini" fontSize="30" maxlength="50" :value.sync="addressInfo.userAddress" placeholder="门牌号等（例如：10栋1001号）"/>
          </view>
        </view>
      </view>
    </view>

    <!--顺手购-->
    <view class="conveniently-buy">
      <p-conveniently v-if="storeInfo" :no-padding="isTemplate3" :store-id="storeInfo.storeId" :product-id="productId" @change="handleChangeConveniently" />
    </view>

    <view class="order-compute">
      <template v-if="!isTemplate3">
        <view class="cell">
          <view class="_lf-title">商品数量</view>
          <view class="_rt">
            共
            <text class="_red">{{ productCountSum }}</text>
            件商品
          </view>
        </view>
        <view class="cell">
          <view class="_lf-title">商品总额</view>
          <view class="_rt">
            <text>
              <text class="font-24 margin-rt-6">¥</text>
              {{ productPriceSum }}
            </text>
          </view>
        </view>
      </template>

      <view class="cell" v-if="directReductionAmount">
        <view class="_lf-title">
          <view class="label">
            <x-icon class="icon" name="icon-094" size="50" color="#E1394C" />
            <view>直降</view>
          </view>
        </view>
        <view class="_rt _red">
          <text style="margin-right: 4px;">
            -
            <text class="font-24 margin-rt-6">¥</text>
            {{ directReductionAmount }}
          </text>
        </view>
      </view>

      <view class="cell" v-if="discountAmount">
        <view class="_lf-title">
          <view class="label">
            <x-icon class="icon" name="icon-090" size="50" color="#E1394C" />
            <view>限时优惠</view>
          </view>
        </view>
        <view class="_rt _red">
          <text style="margin-right: 4px;">
            -
            <text class="font-24 margin-rt-6">¥</text>
            {{ limitedTimeOffer }}
          </text>
        </view>
      </view>
      <view class="cell" v-else-if="superSubsidyAmount">
        <view class="_lf-title">
          <view class="label">
            <x-icon class="icon" name="icon-090" size="50" color="#E1394C" />
            <view>超值补贴</view>
          </view>
        </view>
        <view class="_rt _red">
          <text style="margin-right: 4px;">
            -<text class="font-24 margin-rt-6">¥</text>
            <text>{{ superSubsidyAmount }}</text>
          </text>
        </view>
      </view>
      <view class="cell" v-else-if="couponList && couponList.length" @click="couponVisible = true">
        <view class="_lf-title">
          <view class="label">
            <x-icon class="icon" name="icon-090" size="50" color="#E1394C" />
            <view>优惠券</view>
          </view>
        </view>
        <view class="_rt _red">
          <text v-if="userSelectCoupon" style="margin-right: 4px;">-<text class="font-24 margin-rt-6">¥</text>{{ userSelectCoupon.couponAmount }}</text>
          <text v-else style="margin-right: 4px;" class="font-24">请选择优惠券</text>
          <x-icon name="icon-017" size="28" color="#999999"/>
        </view>
      </view>

      <view class="cell">
        <view class="_lf-title">
          <view class="label">
            <x-icon class="icon" name="icon-092" size="50" color="#E1394C" />
            <view>运费</view>
          </view>
        </view>
        <view class="_rt _red">
          <text style="margin-right: 4px;">
            <text>{{addressInfo.userProvince ? (orderInfo.freightAmount === 0 ? '包邮' : '¥' + orderInfo.freightAmount) : '-'}}</text>
          </text>
        </view>
      </view>

      <template v-if="!isTemplate3">
        <view class="cell" v-if="isDrawer" style="border-bottom: 8px solid #F6F6F6;">
          <view class="_lf-title">买家留言</view>
          <view class="flex1">
            <x-input size="mini" :value.sync="addressInfo.userMessage" placeholder="选填：买家留言"/>
          </view>
        </view>
        <view class="cell" v-if="!isDrawer">
          <view class="_lf-title"></view>
          <view class="_rt">
            <text>应付款：</text>
            <text class="_red" style="font-size: 20px;">
              <text class="font-26 margin-rt-6">¥</text>
              {{ payPrice || ''}}
            </text>
          </view>
        </view>
        <view class="cell" v-if="!isDrawer" style="border-top: 8px solid #F6F6F6;">
          <view class="_lf-title">买家留言</view>
          <view class="flex1">
            <x-input size="mini" :value.sync="addressInfo.userMessage" placeholder="选填：买家留言"/>
          </view>
        </view>
      </template>
    </view>
    <template v-if="isDrawer">
      <div class="section no-padding mt-16">
        <p-privacy v-if="isTemplate3 && isPrivacyEnable" ref="ref-privacy" @onPrivacyBuy="onBuy" />
      </div>
      <view class="m-service-provider">
<!--        <view>页面信息及服务由 <text class="store-name" @click="handleToBusiness">{{ storeInfo.storeName || '' }}（{{ storeInfo.companyName || '' }}）</text> 提供</view>-->
<!--        <view>杭州桃红网络有限公司仅为商家提供技术支持</view>-->
        <view v-if="storeInfo.companyName"><text class="store-name" @click="handleToBusiness">商家： {{ storeInfo.companyName || '' }} | {{ storeInfo.companyAddress || '' }}</text></view>
        <view>商品及服务相关售后，请于微信小程序【{{appName}}】中联系店铺客服获取</view>
        <view v-if="storeInfo.channelCompanyName">【{{storeInfo.channelCompanyName}}】仅提供技术支持 | 4001005802</view>
        <view v-if="storeInfo.channelCompanyName">{{storeInfo.channelCompanyName === '杭州微数数码科技有限公司' ? '浙ICP备2023006219号-2' : '浙ICP备2021000297号-1'}}</view>
      </view>
      <x-fixed ref="x-fixed-bottom" fixed direction="bottom">
        <view class="pay safe-area">
          <!--隐私协议-->
          <p-privacy v-if="!isTemplate3 && isPrivacyEnable" ref="ref-privacy" @onPrivacyBuy="onBuy" />
          <p-charge-details
                            v-if="isTemplate3"
                            :discount-amount-sum="discountPriceSum"
                            :direct-reduction-amount="directReductionAmount"
                            :discount-amount="discountAmount"
                            :super-subsidy-amount="superSubsidyAmount"
                            :coupon-amount="userSelectCoupon.couponAmount"
                            @show-details="handleShowChargeDetails"
                            :show-detail="showChargeDetails"/>
          <p-fixed-discount v-else :price="discountPriceSum" :gift="gift" />
          <view class="_btn">
            <cover-view style="position: absolute;top: 0;width: 100%;height: 100%;background: rgba(0,0,0,0)" @click="onBuy" />
            <x-button size="large" round type="primary" @click="onBuy" styles="background: linear-gradient(270deg, #F85F22 0%, #FFAB80 100%);">
              <view class="btn-buy">
                <text>{{ isNewTemplate ? '立即购买' :'立即支付' }}</text>
                <view class="price" v-if="payPrice">
                  <text>¥</text>
                  <view class="value">
                    <x-count-to :start-val='skuPrice' :end-val='payPrice' :decimals='2' />
                  </view>
                </view>
              </view>
            </x-button>
          </view>
          <view class="safe-area-inset-bottom" />
        </view>
      </x-fixed>
    </template>
    <template v-else>
      <view class="pay safe-area">
        <!--隐私协议-->
        <p-privacy v-if="isPrivacyEnable" ref="ref-privacy" @onPrivacyBuy="onBuy" />
        <p-fixed-discount :price="discountPriceSum" :gift="gift" />
        <view class="_btn">
          <x-button size="large" round type="primary" @click="onBuy">
            {{ isNewTemplate ? `立即购买${payPrice ? ' | ¥'+payPrice : ''}` : '提交订单' }}
          </x-button>
        </view>
      </view>
<!--      <view class="m-service-provider">-->
<!--&lt;!&ndash;        <view>页面信息及服务由 <text class="store-name" @click="handleToBusiness">{{ storeInfo.storeName || '' }}（{{ storeInfo.companyName || '' }}）</text> 提供</view>&ndash;&gt;-->
<!--&lt;!&ndash;        <view>杭州桃红网络有限公司仅为商家提供技术支持</view>&ndash;&gt;-->
<!--        <view><text class="store-name" @click="handleToBusiness">商家： {{ storeInfo.companyName || '' }} | {{ storeInfo.companyAddress || '' }}</text></view>-->
<!--        <view>商品及服务相关售后，请于微信小程序【{{appName}}】中联系店铺客服获取</view>-->
<!--        <view>【{{storeInfo.channelCompanyName}}】仅提供技术支持 | 4001005802</view>-->
<!--        <view>{{storeInfo.channelCompanyName === '杭州微数数码科技有限公司' ? '浙ICP备2023006219号-2' : '浙ICP备2021000297号-1'}}</view>-->
<!--      </view>-->
    </template>
    <!--可使用的优惠券-->
    <p-drawer-coupon
      v-if="couponVisible"
      :visible.sync="couponVisible"
      :value="userSelectUserCouponId"
      :coupon-list="formatCouponList"
      select
      @change="handleChangeUserCoupon"
    />
    <!--取消支付后提示-->
    <x-pay-cancel v-if="payCancelVisible" :visible.sync="payCancelVisible" @confirm="onRepayOrder" @cancel="onCancelPay" />
    <!--取消支付后优惠提示-->
    <x-pay-cancel-pop
      v-if="payCancelTwoVisible && payCancelPopDiscountAmount"
      :visible.sync="payCancelTwoVisible"
      :pic="thumbImg"
      :amount="payCancelPopDiscountAmount"
      @confirm="onRepayOrder"
      @cancel="handleCancelPayPop"
    />
    <x-drawer :visible.sync="showChargeDetails" cancel title="价格明细" background="#F5F5F5" :z-index="110">
      <view class="charge-list">
        <view class="charge-content">
          <view class="order-compute">
            <view class="cell">
              <view class="_lf-title">商品数量</view>
              <view class="_rt">
                共
                <text class="_red">{{ productCountSum }}</text>
                件商品
              </view>
            </view>
            <view class="cell">
              <view class="_lf-title">商品总额</view>
              <view class="_rt">
                <text>
                  <text class="font-24 margin-rt-6">¥</text>
                  {{ productPriceSum }}
                </text>
              </view>
            </view>
            <view class="cell">
              <view class="_lf-title">运费</view>
              <view class="_rt _red">
                <text style="margin-right: 4px;">
                  <text>{{addressInfo.userProvince ? (orderInfo.freightAmount === 0 ? '包邮' : '¥' + orderInfo.freightAmount) : '-'}}</text>
                </text>
              </view>
            </view>
            <view class="cell" v-if="directReductionAmount">
              <view class="_lf-title">直降</view>
              <view class="_rt _red">
                <text style="margin-right: 4px;">
                  -
                  <text class="font-24 margin-rt-6">¥</text>
                  {{ directReductionAmount }}
                </text>
              </view>
            </view>
            <view class="cell" v-if="discountAmount">
              <view class="_lf-title">限时优惠</view>
              <view class="_rt _red">
                <text style="margin-right: 4px;">
                  -
                  <text class="font-24 margin-rt-6">¥</text>
                  {{ limitedTimeOffer }}
                </text>
              </view>
            </view>
            <view class="cell" v-else-if="superSubsidyAmount">
              <view class="_lf-title">超值补贴</view>
              <view class="_rt _red">
                <text style="margin-right: 4px;">
                  -<text class="font-24 margin-rt-6">¥</text>
                  <text>{{ superSubsidyAmount }}</text>
                </text>
              </view>
            </view>
            <view class="cell" v-else-if="couponList && couponList.length && userSelectCoupon">
              <view class="_lf-title">优惠券</view>
              <view class="_rt _red">
                <text style="margin-right: 4px;">-<text class="font-24 margin-rt-6">¥</text>{{ userSelectCoupon.couponAmount }}</text>
              </view>
            </view>
            <view class="cell">
              <view class="_lf-title"></view>
              <view class="_rt">
                <text>应付款：</text>
                <text class="_red" style="font-size: 20px;">
                  <text class="font-26 margin-rt-6">¥</text>
                  {{ payPrice || ''}}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </x-drawer>
  </view>
</template>

<script>
import { promisify, complete } from '@/utils/x-promisify';
import config from '@/config';
import RSA from 'wxmp-rsa';
import $sr from '@/utils/x-sr';
import { mapState } from 'vuex';
import XIcon from '@/components/x-icon';
import XImage from '@/components/x-image';
import XButton from '@/components/x-button';
import XInput from '@/components/x-input';
import XPrice from '@/components/x-price';
import XPayCancel from '@/components/x-pay-cancel';
import XPayCancelPop from '@/components/x-pay-cancel-pop';
import XFixed from '@/components/x-fixed';
import XDrawer from '@/components/x-drawer';
import XCountTo from '@/components/x-count-to';
import PServer from '@/pages/goods-detail/components/p-server';
import PDrawerCoupon from '@/pages/goods-detail/components/p-drawer-coupon';
import PPrivacy from '../p-privacy';
import PFixedDiscount from '../p-fixed-discount';
import PConveniently from '../p-conveniently';
import PSku from './p-sku.vue';
import PCountdown from './p-countdown.vue';
import PChargeDetails from '../p-charge-details';

export default {
  name: 'POrderInfo',
  components: {
    XFixed,
    XIcon,
    XImage,
    XButton,
    XPrice,
    XInput,
    XPayCancel,
    XPayCancelPop,
    PPrivacy,
    PSku,
    PCountdown,
    PServer,
    PConveniently,
    PDrawerCoupon,
    PFixedDiscount,
    PChargeDetails,
    XDrawer,
    XCountTo
  },
  props: {
    isDrawer: {
      type: Boolean,
      default: false
    },
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: () => {}
    },
    productId: {
      type: [String, Number],
      default: ''
    },
    storeInfo: {
      type: Object,
      default: () => {}
    },
    query: {
      type: Object,
      default: () => {}
    },
    pageId: {
      type: String,
      default: ''
    },
    animateEnd: {
      type: Boolean,
      default: false
    },
    discountPriceSum: {
      type: Number,
      default: 0
    },
    gift: {
      type: Number,
      default: 0
    },
    isNewTemplate: {
      type: Boolean,
      default: false
    },
    isTemplate3: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      appName: config.appName,
      navigatorHeight: uni.getWindowInfo().statusBarHeight,
      isSticky: false,
      // 防止快速点击
      clickStatus: true,
      skuVisible: this.visible,
      // 取消支付后弹出提示
      payCancelVisible: false,
      // 取消支付后弹出提示
      payCancelTwoVisible: false,
      // 唤起支付后的订单信息
      payOrderInfo: null,
      index: 0,
      orderInfo: {
        productTotalPrice: ''
      },
      addressInfo: {
        multiIndex: [],
        userName: '',
        userPhone: '',
        addressInfo: '',
        userProvince: '',
        userCity: '',
        userArea: ''
      },
      repay: false, // 判断是否取消订单，唤起二次支付
      // 确认下单
      loading: false,
      // 套餐
      comboSkuInfo: null,
      selectedCombo: null,
      // 多规格
      productSkuInfo: null,
      productSkuList: null,
      skuMode: null,
      productMainPic: null,
      // 优惠券选择层
      couponVisible: false,
      // 用户选择的优惠券
      userSelectUserCouponId: null,
      // 顺手购商品
      incidentallyProduct: null,
      payCancelPopCount: 0,
      payCancelPopDiscountAmount: 0,
      showChargeDetails: false
    };
  },
  watch: {},
  mounted() {
    if (this.isDrawer && this.isExitPopup) {
      const query = uni.createSelectorQuery().in(this);
      query.select('.animate-image-body').boundingClientRect(data => {
        this.$store.dispatch('pages/setData', {
          animateTop: data.top
        });
      }).exec();
    }
  },
  created() {
    // 获取用户上次下单填写的收货地址信息
    uni.getStorage({
      key: 'user-address-info',
      success: (res) => {
        // console.log(res);
        this.addressInfo = res.data;
      },
      complete: () => {
        // 初始化数据
        this.initProductData();
      }
    });

    this.handleCancelPayPop('init');
  },
  computed: {
    ...mapState({
      // app onShow 场景值
      scene: state => state['pages'].scene,
      // 商品数量
      productCount: state => state['pages'].productCount,
      // 隐私勾选状态
      privacyChecked: state => state['pages'].privacyChecked,
      // 是否用户挽留弹窗点击确认
      isConfirmPopup: state => state['pages'].isConfirmPopup,
      // 默认选中的套餐下标
      comboIndex: state => state['pages'].comboIndex,
      // 用户挽留弹框配置的优惠数组
      exitPopupList: state => state['pages'].exitPopupList,
      // 用户挽留弹框配置的优惠展示过的下标
      exitPopupIndex: state => state['pages'].exitPopupIndex,
      // 未支付与挽留弹框状态
      payCancelTwoVisibleAgain: state => state['pages'].payCancelTwoVisibleAgain,
      // 服务承诺
      safeguardList: state => state['product'].safeguardList,
      // 当前商品可使用的优惠券
      couponList: state => state['product'].couponList || [],
      // 用户当前选择的优惠券信息
      userSelectCoupon: state => state['product'].userSelectCoupon,
      // 页面最低价格
      pagePrice: state => state['product'].pageDetail?.pagePrice,
      // 是否使用微信地址按钮
      isShowGetAddress: state => state['product'].pageModule?.getAddress,
      // 是否使用隐私协议
      isShowPrivacy: state => state['product'].pageModule?.privacy,
      // 订单未支付的优惠弹框
      aggregatePage: state => state['product'].pageModule?.aggregatePage,
      // 服务模块
      servicePromise: state => state['product'].pageModule?.servicePromise,
      // 价格模块
      priceModule: state => state['product'].pageModule?.price,
      // 超值补贴模块
      superSubsidyModule: state => state['product'].pageModule?.superSubsidy,
      // 已选套餐规格
      userSelectSku: state => state['product'].userSelectSku,
      // 页面单买价
      pageHighPrice: state => state['product'].pageDetail?.pageHighPrice,
      // 划线价
      crossedPrice: state => state['product'].pageModule.crossedPrice
    }),
    // 处理当前可使用的优惠券数据
    formatCouponList() {
      return this.couponList?.map(item => {
        const price = (this.productCount * this.skuPrice) - this.promotionDiscountAmount;
        return {
          ...item,
          disabled: item.couponType === 1 && item.transactionAmount > price
        };
      });
    },
    // 商品总数量
    productCountSum() {
      return this.incidentallyProduct ? this.productCount + 1 : this.productCount;
    },
    // 商品总金额
    productPriceSum() {
      let price = this.productCount * this.skuOriginalPrice;
      if (this.incidentallyProduct) {
        price += this.incidentallyProduct.additionalActivityPrice;
      }
      return this.$tools.formatNumber(price);
    },
    // 大促展示样式
    isPromotion() {
      return this.priceModule && this.priceModule.value === 2;
    },
    // 超值补贴
    isSuperSubsidy() {
      return this.superSubsidyModule && this.superSubsidyModule.value;
    },
    // 挽留弹框状态
    isExitPopup() {
      return !this.repay && this.payCancelTwoVisibleAgain;
    },
    // 限时优惠金额-单价
    discountAmount() {
      let amount = 0;
      if (this.isFromCouponCards) {
        return 0;
      }
      if (this.repay && this.payCancelPopDiscountAmount) {
        // 下单未支付优惠金额
        amount = this.payCancelPopDiscountAmount;
      } else if (this.isExitPopup) {
        // 挽留优惠金额
        amount = this.currentExitPopupAmount;
      } else if (this.query?.discountAmount) {
        // url参数上带的优惠金额
        amount = Number(this.query.discountAmount);
      } else if (this.query?.useDiscount && this.aggregatePage?.discountAmount) {
        // url参数上带的需要使用最大优惠金额的标识时，使用最大优惠金额
        amount = Number(this.aggregatePage?.discountAmount);
      }
      return amount || 0;
    },
    // 限时优惠金额-算上数量
    limitedTimeOffer() {
      return this.formatNumber(this.discountAmount);
    },
    // sku拼单价
    skuPrice() {
      let price = this.currentSku?.skuGroupPrice || this.pagePrice;
      if (this.detail.skuMode === 1) {
        // 单规格使用页在价格
        price = this.pagePrice;
      }
      return this.$tools.formatNumber(price);
    },
    // sku单买价
    skuOriginalPrice() {
      let price = this.currentSku?.skuPrice || this.pageHighPrice;
      if (this.detail.skuMode === 1) {
        // 单规格使用页在价格
        price = this.pageHighPrice;
      }
      return this.$tools.formatNumber(price);
    },
    // 大促金额
    promotionDiscountAmount() {
      return this.isPromotion ? this.priceModule.discountAmount : 0;
    },
    // 超值补贴金额
    superSubsidyAmount() {
      return (this.isSuperSubsidy && !this.isFromCouponCards) ? this.superSubsidyModule.value : 0;
    },
    // 是否从优惠券卡片进来
    isFromCouponCards() {
      return ['1008'].includes(this.query.source);
    },
    // 券后价
    skuCouponPrice() {
      let price = this.skuPrice;
      if (this.userSelectCoupon) {
        const couponAmount = this.orderInfo?.couponAmount || this.userSelectCoupon?.couponAmount || 0;
        price -= couponAmount;
      }
      if (price <= 0) {
        price = 0.01;
      }
      return this.$tools.formatNumber(price);
    },
    // 当前挽留弹窗数据
    currentExitPopup() {
      return this.exitPopupList?.length ? this.exitPopupList[this.exitPopupIndex - 1] : null;
    },
    // 当前挽留弹窗优惠信息
    currentExitPopupAmount() {
      if (this.currentExitPopup) {
        return this.currentExitPopup.discountAmount;
      }
      return 0;
    },
    // sku原价 - 大促金额 - 限时价
    againBuyPrice() {
      let price = this.skuPrice;
      if (this.discountAmount) {
        price -= this.discountAmount;
      }
      if (price <= 0) {
        price = 0.01;
      }
      return this.$tools.formatNumber(price);
    },
    // 需要支付金额
    payPrice() {
      // 大促金额，一个订单只减一次大促价，不跟数量走
      const price = (this.skuPrice * this.productCount - this.promotionDiscountAmount);
      let discountPriceSum = this.directReductionAmount;
      let priceSum = price;
      if (this.discountAmount) {
        // 挽留下，使用挽留优惠金额
        priceSum = price - this.limitedTimeOffer;
        discountPriceSum += this.limitedTimeOffer;
      } else if (this.superSubsidyAmount) {
        priceSum = price - this.superSubsidyAmount;
        discountPriceSum += this.superSubsidyAmount;
      } else if (this.userSelectCoupon) {
        // 匹配到优惠券，优先使用优惠券
        priceSum = price - (this.userSelectCoupon ? this.userSelectCoupon.couponAmount : 0);
        discountPriceSum += this.userSelectCoupon.couponAmount;
      }

      this.$emit('update:discount-price-sum', this.$tools.formatNumber(discountPriceSum));
      if (priceSum <= 0) {
        priceSum = 0.01;
      }
      // 加上运费
      if (this.orderInfo.freightAmount) {
        priceSum += this.orderInfo.freightAmount;
      }
      // 加上顺手购买商品金额
      if (this.incidentallyProduct) {
        priceSum += this.incidentallyProduct.additionalActivityPrice;
      }
      return this.$tools.formatNumber(priceSum);
    },
    getCurrentPath() {
      const currPath = ['/pages/advertising/index'];
      const query = this.query;
      // 订阅消息场景获取
      try {
        // 当用户通过订阅消息场景值（1014、1107）下单时，本地缓存的订阅消息模板ID上报
        const storageMessageTemplateId = uni.getStorageSync('MESSAGE-TEMPLATE-ID');
        if ([1014, 1107].includes(this.scene) && storageMessageTemplateId) {
          Object.assign(query, {
            messageTemplateId: storageMessageTemplateId,
            source: 1009
          });
        }
      } catch (e) {
        console.warn('messageTemplateId-> ', e);
      }
      const params = this.$tools.object2param(query);
      if (params) currPath.push(params);
      return currPath.join('?');
    },
    // 隐私协议
    isPrivacyEnable() {
      return this.isShowPrivacy;
    },
    showAnimateBanner() {
      return this.limitedTimeOffer || (!this.superSubsidyAmount && this.orderInfo.couponAmount);
    },
    // 横幅banner class
    animateBannerClassName() {
      const arr = ['animate-image'];
      if (this.animateEnd || this.orderInfo?.couponAmount || this.discountAmount || this.superSubsidyAmount) {
        arr.push('_zoomIn');
      }
      return arr.join(' ');
    },
    // 匹配当前选中的sku详细数据
    currentSku() {
      if (this.productSkuList) {
        return this.productSkuList.find(item => item.attr.every((spec) => spec.value === this.productSkuInfo.find((s) => s.name === spec.name)?.selected));
      } else {
        return null;
      }
    },
    // 匹配当前选中的套餐
    currentCombo() {
      if (this.comboSkuInfo) {
        return this.comboSkuInfo.find(item => item.id === this.selectedCombo);
      } else {
        return null;
      }
    },
    // 商品规格图
    thumbImg() {
      return this.currentSku?.thumbImg ? this.currentSku.thumbImg : this.detail.productMainPic;
    },
    // 直降金额：单买价-拼单价
    directReductionAmount() {
      return this.$tools.formatNumber((this.skuOriginalPrice - this.skuPrice) * this.productCount) || 0;
    }
  },
  methods: {
    // 格式化商品相关数据
    initProductData() {
      const { comboSkuInfo, productSkuInfo, productSkuList, productMainPic, skuMode } = this.detail || {};
      const { gdt_vid, adid, ksUnitId, hq_vid, source } = this.query || {};
      if (!(gdt_vid || adid || ksUnitId || hq_vid) || ['1028', '1029', '1030'].includes(source)) {
        // 无广告id的时候，自动选择一张优惠券
        const price = (this.productCount * this.skuPrice) - this.promotionDiscountAmount;
        const coupon = this.$tools.matchBestCoupon(this.couponList, price);
        this.$store.dispatch('product/setData', {
          userSelectCoupon: coupon
        });
        this.userSelectUserCouponId = coupon?.userCouponId;
      }
      // 无规格商品可直接下单
      // skuMode 规格模式：1-统一规格；2-多规格；3-套餐模式
      if (skuMode === 1) {
        this.getOrderInfo();
      } else {
        if (this.userSelectSku && this.userSelectSku.productId === this.productId) {
          // 有缓存的sku
          Object.assign(this, {
            selectedCombo: this.userSelectSku.selectedCombo,
            comboSkuInfo: this.userSelectSku.comboSkuInfo,
            productSkuInfo: this.userSelectSku.productSkuInfo,
            productSkuList: this.userSelectSku.productSkuList,
            productMainPic,
            skuMode
          });
        } else {
          let selectedCombo;
          if (skuMode === 3) {
            // 默认选中第一个套餐
            const { id } = comboSkuInfo[0];
            selectedCombo = id;
          }

          // console.log(JSON.stringify(productSkuInfo));
          // console.log(comboSkuInfo);
          Object.assign(this, {
            selectedCombo,
            comboSkuInfo,
            productSkuInfo,
            productSkuList,
            productMainPic,
            skuMode
          });
        }
        this.getOrderInfo();
      }

      // 价格公式
      // 初始时：（sku原价 - 补贴价），券后价：（sku原价 - 补贴价 - 优惠券）
      // 挽留时：（sku原价 - 补贴价 - 优惠券 - 限时价），划线价：（sku原价 - 补贴价 - 优惠券）
      // 投放页，当有广告ID或者挽留弹窗状态下，任何优惠券都不可以被使用
    },
    formatNumber(val) {
      return this.$tools.formatNumber(val);
    },
    previewImage() {
      this.$store.dispatch('pages/setData', {
        clearStoreStorage: false
      });
      this.$XTrack('previewImage', {
        urls: this.thumbImg
      });
      uni.previewImage({
        urls: [this.thumbImg]
      });
    },
    scrollTab() {
      const view = uni.createSelectorQuery().in(this);
      view.select('._header-top').boundingClientRect(res => {
        // 是否为固定悬浮状态
        this.isSticky = res.top <= this.navigatorHeight + 44 + 5;
      }).exec();
    },
    formatZero(val) {
      return this.$tools.formatZero(val);
    },
    // 格式化图片
    formatOss(url) {
      return this.$tools.formatOss(url, 200);
    },
    // 数量加减
    handleAddCount() {
      this.$store.dispatch('pages/setData', {
        productCount: this.productCount + 1
      });
      this.getOrderInfo();
      this.$XTrack('productCountChangeEvent');
    },
    handleReduceCount() {
      this.$store.dispatch('pages/setData', {
        productCount: this.productCount - 1
      });
      this.checkUserCoupon();
      this.getOrderInfo();
      this.$XTrack('productCountChangeEvent');
    },
    // 判断可否使用/并使用最优优惠券
    checkUserCoupon() {
      if (this.userSelectCoupon) {
        const { couponType, transactionAmount } = this.userSelectCoupon;
        const price = (this.productCount * this.skuPrice) - this.promotionDiscountAmount;
        if (couponType === 1 && price < transactionAmount) {
          this.$store.dispatch('product/setData', {
            userSelectCoupon: null
          });
          this.userSelectUserCouponId = null;
        }
      }
    },
    // 获取微信地址
    async onAddress() {
      await this.$store.dispatch('pages/setData', {
        clearStoreStorage: false
      });
      const scope = 'scope.address';
      const { authSetting } = await promisify(uni.getSetting)();
      console.info('uni.getSetting => ', authSetting);
      if (authSetting?.hasOwnProperty(scope)) {
        if (!authSetting[scope]) {
          await promisify(uni.openSetting)();
        }
      } else {
        await complete(uni.authorize)({ scope });
      }

      uni.chooseAddress({
        success: res => {
          this.addressInfo = {
            userName: res.userName,
            userPhone: res.telNumber,
            multiIndex: [res.provinceName, res.cityName, res.countyName],
            addressInfo: res.provinceName + '-' + res.cityName + '-' + res.countyName,
            userAddress: res.detailInfo,
            userProvince: res.provinceName,
            userCity: res.cityName,
            userArea: res.countyName
          };
          this.getOrderInfo('chooseAddress');
          this.$XTrack('chooseAddressEvent');
        },
        fail: () => {
        }
      });
    },
    // 区域选择
    multiChange(e) {
      const detail = e.detail.value;
      this.addressInfo.addressInfo = detail[0] + '-' + detail[1] + '-' + detail[2];
      this.addressInfo.multiIndex = e.detail.value;
      this.addressInfo.userProvince = detail[0];
      this.addressInfo.userCity = detail[1];
      this.addressInfo.userArea = detail[2];
      this.getOrderInfo('chooseAddress');
      this.$XTrack('inputRegionChangeEvent', e.detail.value); // 数据埋点，选择地址改变
    },
    async getOrderInfo(type) {
      const params = {
        pageId: this.pageId,
        productId: this.productId, // 商品ID
        skuId: this.currentSku?.id, // skuId
        productCount: this.productCount, // 商品数量
        orderType: 1, // 订单类型：1-普通订单；2-开团；3-参团
        userCouponId: this.userSelectCoupon?.userCouponId, // 优惠券ID
        userProvince: this.addressInfo?.userProvince, // 用户省份
        userCity: this.addressInfo?.userCity, // 用户城市
        userArea: this.addressInfo?.userArea, // 用户区域
        incidentallyProductId: this.incidentallyProduct?.productId, // 顺手购商品ID
        additionalActivityId: this.incidentallyProduct?.additionalActivityId // 顺手购活动ID
      };
      if (this.addressInfo?.userProvince) {
        this.$emit('update:address-info', this.addressInfo);
      }
      await this.$http({
        login: true,
        url: '/product/spu/order/info',
        method: 'post',
        data: params,
        report: true
      }).then(res => {
        this.orderInfo = res.data || {};
        if (type === 'submit') {
          this.onBuy();
        }
        // 切换spu时回调到外层
        this.$emit('change-spu', this.orderInfo, this.isExitPopup);
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    async onBuy() {
      if (this.loading) return;
      // 点击购买按钮
      this.$XTrack('orderSaveStart');

      // 校验隐私协议
      try {
        if (this.isPrivacyEnable && !this.privacyChecked) {
          this.$XTrack('privacy_checked', {
            checked: false
          });
          this.$refs['ref-privacy'].handleShowRemind();
          return false;
        }
      } catch (e) {
        console.warn('校验隐私协议出错了');
      }
      if (!this.addressInfo.userName.trim()) {
        if (this.isTemplate3) {
          uni.showToast({
            title: '请填写收货地址！',
            icon: 'none'
          });
        } else {
          uni.showToast({
            title: '请填写收货人姓名！',
            icon: 'none'
          });
        }
        return false;
      }
      if (!this.addressInfo.userPhone) {
        uni.showToast({
          title: '请填写收货人手机号！',
          icon: 'none'
        });
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.addressInfo.userPhone)) {
        uni.showToast({
          title: '手机号格式输入不正确！',
          icon: 'none'
        });
        return false;
      }
      if (!this.addressInfo.addressInfo) {
        uni.showToast({
          title: '请选择省市区！',
          icon: 'none'
        });
        return false;
      }
      if (!this.addressInfo.userAddress) {
        uni.showToast({
          title: '请填写收货人详细地址！',
          icon: 'none'
        });
        return false;
      }
      if (this.clickStatus === true) {
        this.clickStatus = false;
      } else {
        uni.showToast({
          title: '请勿重复点击！',
          icon: 'none'
        });
        return false;
      }
      // 默认广告点击下单
      const groupsSource = +this.query.groupsSource;
      let submitOrderClickValue = 1001;
      // 点击挽留弹窗确认之后的下单
      if (this.isConfirmPopup) {
        submitOrderClickValue = 1002;
      }
      // 通过挽留页或者其它来源的下单
      if (this.query.source && this.query.source !== 'stay') {
        submitOrderClickValue = 1003;
      }
      // 有明确挽留来源的下单
      if (groupsSource) {
        submitOrderClickValue = groupsSource;
      }
      this.$XTrack('submitOrderClickEvent', {
        from: this.isDrawer ? 'drawer' : 'ordinary',
        value: submitOrderClickValue
      });

      const { sourcePageType, sourcePageId, source, pageType } = this.query;
      const params = {
        productId: this.productId, // 商品ID
        pageId: this.pageId, // 页面ID
        orderType: 1, // 订单类型：1-普通订单；2-开团；3-参团
        userName: this.addressInfo.userName, // 收件人姓名
        userPhone: this.addressInfo.userPhone, // 收件人手机号
        userProvince: this.addressInfo.multiIndex[0], // 省
        userCity: this.addressInfo.multiIndex[1], // 市
        userArea: this.addressInfo.multiIndex[2], // 区
        // 详细地址
        userAddress: this.addressInfo.userAddress,
        // 用户留言
        userMessage: this.addressInfo.userMessage,
        // 购买数量
        productCount: this.productCount,
        // 页面地址
        pageUrl: this.getCurrentPath,
        // 落地页Id  通过聚合页下单传
        landingPageId: sourcePageId || '',
        // 落地页类型：1-基础图文落地页；2-沉浸式视频落地页
        landingPageType: parseInt(sourcePageType || pageType) || 1,
        orderScene: this.scene,
        // 顺手购买商品
        incidentallyProductId: this.incidentallyProduct?.productId,
        // 顺手购活动Id
        additionalActivityId: this.incidentallyProduct?.additionalActivityId
      };

      // 限时优惠金额-进行优惠-只传单个的优惠金额
      if (this.discountAmount) {
        Object.assign(params, {
          preferentialAmount: this.discountAmount
        });
      } else if (this.superSubsidyAmount) {
        Object.assign(params, {
          subsidyAmount: this.superSubsidyAmount
        });
      } else if (this.userSelectCoupon) {
        // 有匹配的优惠券就使用优惠券
        const coupon = this.userSelectCoupon || null;
        if (coupon) {
          Object.assign(params, {
            userCouponId: coupon.userCouponId,
            couponCreatedType: coupon.createdType
          });
        }
      }
      // 回流数据区分
      // refluxType 回流类型：1-挽留弹框；2-下单未支付弹框；3-聚合页；4-优惠券
      try {
        const { popupIndex, moduleId, styleType } = this.currentExitPopup || {};
        let refluxType;
        switch (source) {
          case 'stay':
            refluxType = 1;
            Object.assign(params, {
              moduleId,
              // 从1开始
              popupIndex: popupIndex + 1,
              refluxPopupStyle: styleType
            });
            break;
          case '1026':
          case 'groups':
            refluxType = 3;
            break;
          case '1008':
            refluxType = 4;
            break;
          default:
            break;
        }
        if (refluxType) {
          Object.assign(params, {
            refluxType
          });
        }
      } catch (e) {
        console.warn('回流数据区分 error -> ', e);
      }

      // skuId
      if (this.currentSku?.id) {
        params.skuId = this.currentSku.id;
      }

      // 部分数据进行加密处理
      const rsa = new RSA();
      rsa.setPublicKey(config.publicKey);
      params.userName = rsa.encryptLong(params.userName);
      params.userPhone = rsa.encryptLong(params.userPhone);
      params.userAddress = rsa.encryptLong(params.userAddress);

      // 下单api接口
      this.loading = true;
      this.$http({
        login: true,
        url: '/order/order/asymmetric/save',
        method: 'post',
        data: params,
        alarm: true
      }).then(res => {
        const wxParams = res.data;
        this.payOrderInfo = res.data;
        this.clickStatus = true;
        this.srTrack('give_order');
        this.$XTrack('orderSuccessInfo', {
          pageId: this.pageId,
          productId: this.productId,
          orderId: res.data.orderId,
          couponInfo: this.userSelectCoupon,
          discountAmount: this.discountAmount
        });
        try {
          // 下单完成之后保存收货地址
          if (this.addressInfo.userMessage) {
            delete this.addressInfo.userMessage;
          }
          uni.setStorage({
            key: 'user-address-info',
            data: this.addressInfo
          });
          this.srTrack('pay');
        } catch (err) {
          this.$store.dispatch('app/setAlarm', {
            code: 'AppOnError',
            message: err,
            url: 'p-order-info,vue',
            requestData: {},
            header: {}
          });
        }
        uni.requestPayment({
          orderInfo: wxParams.orderInfo,
          timeStamp: wxParams.timeStamp,
          paySign: wxParams.paySign,
          nonceStr: wxParams.nonceStr,
          signType: wxParams.signType,
          package: wxParams.package,
          success: () => {
            this.srTrack('payed');
            //  初始化页面状态
            this.$store.dispatch('pages/fetchAppStore');

            // 清除首页限时浮层数据
            this.$store.dispatch('product/setData', {
              homeReLaunchUrl: null
            });
            // 埋点
            this.$XTrack('orderPaySuccess', {
              pageId: this.pageId,
              productId: this.productId,
              orderId: res.data.orderId,
              couponInfo: this.userSelectCoupon,
              discountAmount: this.discountAmount
            });
            this.$store.dispatch('message/requestSubscribeMessage', {
              subscribeNode: 1,
              subscribeType: 1,
              subscribeContent: this.pageId,
              storeId: this.storeInfo?.storeId
            }).then(() => {
              uni.reLaunch({
                url: `/packages/order/pay-status/index?orderId=${wxParams.orderId}`
              });
            }).catch(() => {
              uni.reLaunch({
                url: `/packages/order/pay-status/index?orderId=${wxParams.orderId}`
              });
            });
          },
          fail: (err) => {
            // console.log(err);
            this.clickStatus = true;
            try {
              this.$XTrack('errorOrderPay', err.errMsg);
              if (err.errMsg.includes('cancel')) {
                this.$XTrack('cancelOrderPay', wxParams);
                // 如果当前已经是最大优惠了，那么不显示下单未支持弹层
                // 使用优惠券的场景下，不显示下单未支持弹层
                if (!this.userSelectCoupon && this.payCancelPopDiscountAmount > this.discountAmount || 0) {
                  this.payCancelTwoVisible = true;
                  // 取消支付，可以使用优惠金额支付了
                  this.repay = true;
                } else {
                  this.payCancelVisible = true;
                }
                // 有数上报，取消支付
                this.srTrack('cancel_pay');
              }
            } catch (e) {
              this.clickStatus = true;
              console.log(e);
            }
          },
          complete: () => {
            this.loading = false;
          }
        });
      }).catch(err => {
        this.loading = false;
        this.clickStatus = true;
        try {
          // 商品id与sku id 不匹配的时候，尝试修正数据
          if (/8700/.test(err.code)) {
            this.$XTrack('repairOrderProductNotMatch', {
              productId: params.productId,
              skuId: this.currentSku?.id
            });
            this.$store.dispatch('pages/setData', { comboIndex: 0 });
            this.$store.dispatch('product/getProductDetail', {
              pageId: params.pageId,
              productId: params.productId
            }).then(() => {
              // 重新初始化
              this.initProductData();
            });
          }
        } catch (e) {
          console.warn('order save-> ', e);
        }
        console.log(err);
      });
    },
    // 下单未支付，进行重新支付
    onRepayOrder() {
      if (this.loading) return;
      const params = {
        orderId: this.payOrderInfo.orderId,
        incidentallyOrderId: this.payOrderInfo.incidentallyOrderId
      };
      if (!this.userSelectCoupon && this.payCancelPopDiscountAmount >= this.discountAmount || 0) {
        Object.assign(params, {
          preferentialAmount: this.payCancelPopDiscountAmount || 0,
          refluxType: 2
        });
        // 埋点 取消支付有优惠金额的重新支付
        this.$XTrack('onRepayNewEvent');
      } else {
        this.$XTrack('onRepayEvent');
      }
      this.loading = true;
      this.$http({
        login: true,
        url: '/order/order/repay',
        method: 'post',
        data: params,
        alarm: true
      }).then(res => {
        const wxParams = res.data;
        this.payOrderInfo = res.data;
        // 有数上报，支付
        this.srTrack('pay');
        uni.requestPayment({
          orderInfo: wxParams.orderInfo,
          timeStamp: wxParams.timeStamp,
          paySign: wxParams.paySign,
          nonceStr: wxParams.nonceStr,
          signType: wxParams.signType,
          package: wxParams.package,
          success: () => {
            this.srTrack('payed');
            //  初始化页面状态
            this.$store.dispatch('pages/fetchAppStore');
            this.$XTrack('orderPaySuccess', Object.assign(this.payOrderInfo, {
              isRepay: true,
              preferentialAmount: this.payCancelPopDiscountAmount
            }));
            // 下单完成之后保存收货地址
            delete this.addressInfo.userMessage;
            uni.setStorage({
              key: 'user-address-info',
              data: this.addressInfo
            });
            uni.reLaunch({
              url: `/packages/order/pay-status/index?orderId=${wxParams.orderId}`
            });
          },
          fail: (err) => {
            try {
              this.$XTrack('errorOrderPay', err.errMsg);
              if (err.errMsg.includes('cancel')) {
                // this.payCancelVisible = true;
                this.handleCancelPayPop();
                // 有数上报，取消支付
                this.srTrack('cancel_pay');
              }
            } catch (e) { console.log(e); }
          },
          complete: () => {
            this.loading = false;
          }
        });
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    onCancelPay() { // 重新唤起支付并且取消支付
      //  初始化页面状态
      this.$store.dispatch('pages/fetchAppStore');
      const orderId = this.payOrderInfo.orderId;
      uni.reLaunch({
        url: `/packages/order/detail/index?orderId=${orderId}`,
        complete() {
          setTimeout(() => {
            uni.hideLoading();
          }, 1000);
        }
      });
      this.$XTrack('cancelOrderPayEvent');
    },
    // 输入完手机号之后获取是否有已经存在的地址信息
    handleBlurPhone(val) {
      if (/^1[3-9]\d{9}$/.test(val)) {
        this.$http({
          report: false,
          url: '/order/address/app/detail',
          data: {
            userPhone: val
          }
        }).then((res) => {
          if (res.data) {
            const { userAddress, userArea, userCity, userName, userProvince } = res.data;
            if (!this.addressInfo.userName) {
              this.addressInfo.userName = userName;
            }
            if (!this.addressInfo.userProvince) {
              Object.assign(this.addressInfo, {
                multiIndex: [userProvince, userCity, userArea],
                addressInfo: `${userProvince}-${userCity}-${userArea}`,
                userProvince: userProvince,
                userCity: userCity,
                userArea: userArea,
                userAddress: userAddress
              });
            }
          }
        });
      }
    },
    // 有数上报
    // give_order：用户提交订单；
    // pay：用户发起支付；
    // cancel_pay：用户关闭支付密码浮层；
    // payed：用户完成支付（影响有数实时订单统计）；
    // cancel_give_order：用户取消订单；
    // refund：用户发起退货退款
    srTrack(status) {
      try {
        const { orderInfo } = this.payOrderInfo;
        const { price_info, product_infos } = orderInfo.order_detail;

        // 优惠前的商品总价
        let orderAmt = 0;
        product_infos.forEach(item => {
          orderAmt += (item.sale_price * item.product_cnt);
        });
        $sr.track('custom_order', {
          'order': {
            'order_id': orderInfo.out_order_id,
            'order_time': +new Date(orderInfo.create_time.replace(/-/gi, '/')),
            'order_status': status
          },
          'sub_orders': [{
            'sub_order_id': orderInfo.out_order_id,
            'order_amt': this.$tools.formatNumber(orderAmt / 100),
            'pay_amt': this.$tools.formatNumber(price_info.order_price / 100)
          }]
        });
      } catch (e) {
        console.log('srTrack->', e);
      }
    },
    // 跳转店铺资质页
    handleToBusiness() {
      const { appName } = config;
      const { storeId, storeName } = this.storeInfo;
      const { pageId } = this.query;
      uni.navigateTo({
        url: `/packages/store/business?storeId=${storeId}&storeName=${storeName || appName}&pageId=${pageId}`
      });
    },
    // 切换套餐
    handleChangeCombo(item) {
      if (item.id !== this.selectedCombo) {
        Object.assign(this, {
          selectedCombo: item.id,
          productSkuInfo: item.skuInfo,
          productSkuList: item.skuList
        });
        this.handleChangeSku();
      }
    },
    // 切换sku
    handleChangeSku() {
      // console.log(JSON.stringify(this.currentSku));
      this.checkUserCoupon();
      this.getOrderInfo();

      this.$emit('sku-change', this.currentSku);
      this.$store.dispatch('product/setSelectedSku', {
        productId: this.productId,
        selectedCombo: this.selectedCombo,
        comboSkuInfo: this.comboSkuInfo,
        productSkuInfo: this.productSkuInfo,
        productSkuList: this.productSkuList
      });
    },
    // 切换顺手购商品
    handleChangeConveniently(product) {
      this.incidentallyProduct = product;
    },
    // 用户切换使用优惠券
    handleChangeUserCoupon(coupon) {
      this.$store.dispatch('product/setData', {
        userSelectCoupon: coupon
      });
      this.userSelectUserCouponId = coupon?.userCouponId;
    },
    // 取消下单未支付操作
    handleCancelPayPop(state) {
      if (this.userSelectCoupon) {
        if (state !== 'init') {
          this.payCancelVisible = true;
        }
        return false;
      } else if (this.exitPopupList?.length) {
        try {
          this.payCancelPopDiscountAmount = this.discountAmount || this.superSubsidyAmount;
          const array = this.exitPopupList.map(item => {
            return item.discountAmount;
          });
          array.push(this.aggregatePage.discountAmount);
          const list = [...new Set(array.sort((a, b) => a - b))].filter(item => item > this.payCancelPopDiscountAmount);
          console.log(list, this.payCancelPopDiscountAmount);
          if (list.length) {
            this.payCancelPopDiscountAmount = list[0];
            console.log(this.payCancelPopDiscountAmount);
            if (state !== 'init') {
              setTimeout(() => {
                this.payCancelTwoVisible = true;
              }, 200);
            }
          } else {
            if (state !== 'init') {
              this.payCancelVisible = true;
            }
          }
        } catch (e) {
          if (state !== 'init') {
            this.payCancelVisible = true;
          }
        }
      } else {
        if (state !== 'init') {
          this.payCancelVisible = true;
        }
      }
    },

    handleShowChargeDetails() {
      this.showChargeDetails = !this.showChargeDetails;
    }
  }
};
</script>

<style lang="scss" scoped>
._header-top{
  z-index: 88;
  background: #FFFFFF;
  .selected-sku-box{
    display: flex;
    padding: 24px;border-bottom: 1px solid $uni-page-bg;
  }
  ._lf{
    width: 130px;
    height: 130px;
    border-radius: 10px;
    background: #FFECEC;
    margin-right: 18px;
    overflow: hidden;
    position: relative;
    ._icon-zoom-in {
      position: absolute;
      top: 8px;
      right: 8px;
      background: rgba(0, 0, 0, 0.2);
      display: flex;
      width: 40px;
      height: 40px;
      border-radius: 40px;
      align-items: center;
      justify-content: center;
    }

    &.small{
      width: 100px;
      height: 100px;
    }
  }
  ._rt{
    flex: 1;
    display: flex;
    flex-direction: column;
    //align-items: center;
    ._price{
      display: flex;
      align-items: center;
      flex: 1;
      width: 100%;
      font-size: 28px;
      color: $uni-color-primary;
      .original{
        color: #6E6E6E;
        font-size: 46px;
        text-decoration: line-through;
      }
      ._coupon-price{
        display: flex;
        align-items: baseline;
        margin-bottom: 8px;
        margin-left: 20px;
        min-width: 184px;
        height: 54px;
        line-height: 54px;
        background: linear-gradient(270deg, #FF3A0F 0%, #FF7C32 100%);
        border-radius: 100px;
        text-align: center;
        color: #FFFFFF;
        font-size: 40px;
        padding: 0 14px;
        //margin-top: 8px;
        ._coupon-after{
          padding: 0 4px;
          font-size: 26px;
        }
      }
      ._line-through{
        font-size: 32px;
        color: #999999;
        text-decoration: line-through;
        margin-left: 10px;
      }
    }
    ._text{
      width: 100%;
      font-size: 28px;
      color: $uni-color-secondary;
      -webkit-line-clamp: 1;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 16px;
      ._tagselect{
        margin-left: 10px;
      }
    }
    ._num{
      display: flex;
      align-items: center;
      ._num_rt{
        display: flex;
        ._num{
          width: 76px;
          height: 48px;
          background: #F2F3F5;
          margin: 0 4px;
          padding: 0;
          overflow: hidden;
        }
        ._jian{
          width: 48px;
          height: 48px;
        }
      }
    }
  }
  .icon{
    position: absolute;
    top: 24px;
    right: 24px;
  }
}
.animate-image-body{ background: #FFFFFF;}
.animate-image{
  height: 0; width: 100%; background: #FA335C cdn('/images/bg-coupon-1.png') no-repeat; background-size: cover; display: flex;  align-items: center; opacity: 0; transition: .5s;
  &._zoomIn{ opacity: 1; height: 130px;}

  ._lf{
    flex: 1;
    ._content{
      padding: 26px 24px 20px 24px; color: #FFFFFF;
      ._t1{ font-size: 26px;}
      ._t2{
        font-size: 34px; font-weight: 400;
        text{ color: #FFE81D;}
      }
    }
  }
}
@keyframes zoomIn {
  from {
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }
  50%, 100% {
    opacity: 1;
  }
}
.drawer-header{
  .address{
    min-height: 120px;padding: 24px; background: #FFFFFF;align-items: center;
    ._lf{
      margin-right: 12px;
      ._img{
        width: 36px;
        height: 36px;
      }
    }
    ._user-info{
      font-size: 32px;
      color: $uni-color-default;
      font-weight: bold;
      margin-bottom: 12px;
      ._text{
        font-size: 28px;
      }
    }
    .add-address{
      font-size: 28px;
      color: $uni-color-default;
    }
    .address-info{
      font-size: 28px;
      color: $uni-color-info;
      -webkit-line-clamp: 2;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: justify;
    }
  }
}
.p-set-order{
  position: relative;
  background: #FFFFFF;
  border-radius: 20px 20px 0px 0px;
  //padding: 24px 0 0 0;
  //padding-bottom: env(safe-userArea-inset-bottom);
  width: 100%;
  height: 100%;

  ._scroll{
    position: relative;
    //padding: 0 24px;
    // add
    // end
    ._num{
      display: flex;
      padding: 16px 24px;
      align-items: center;
      border-bottom: 1px solid $uni-page-bg;
      ._lf{
        flex: 1;
        color: $uni-color-default;
        font-size: 30px;
        display: flex;
      }
      ._rt{
        display: flex;
        ._num{
          width: 76px;
          height: 64px;
          background: #F2F3F5;
          margin: 0 4px;
          padding: 0;
        }
        ._jian{
          width: 64px;
          height: 64px;
        }
      }
    }
  }
  ._bottom{
    box-shadow: 0px -4px 8px rgba(230, 177, 177, 0.2);padding-bottom: 1px;
    ._tips{
      text-align: center;
      font-size: 28px;
      color: $uni-color-info;
      padding: 16px;
      ._red{
        color: $uni-color-primary;
        margin: 0 4px;
      }
    }
    ._bottom-fixed{
      ._btn{
        width: 702px;
        margin: 16px 24px 32px 16px;
      }
    }
  }
}
.p-address{
  margin-top: 16px;
  background: #FFFFFF;
  ._title{
    padding: 30px 24px;
    display: flex;
    border-bottom: 2px solid #eeeeee;
    ._lf{
      flex: 1;
      font-size: 30px;
      color: $uni-color-default;
    }
    ._rt{
      display: flex;
      align-items: center;
      font-size: 28px;
      color: $uni-color-success;
      ._use-WeiXin{
        margin-right: 4px;display: flex;align-items: center;
      }
    }
  }
  .cell-group{
    .cell{
      display: flex;
      align-items: center;
      padding: 0px 24px;
      height: 100px;
      border-bottom: 2px solid #eeeeee;
      ._lf-title{
        min-width: 112px;
        font-size: 30px;
        color: $uni-color-default;
        margin-right: 28px;
      }
      .adress-info{
        font-size: 30px;
      }
      .region-picker {
        overflow: hidden;
        width: 500px;
      }

      .region-item {
        &:last-child {
          margin-right: 0;
        }

        position: relative;
        width: 33%;
        line-height: 72px;
        padding-right: 30px;
        margin-right: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        &:after {
          content: '';
          position: absolute;
          top: 30px;
          right: 6px;
          border: 14px solid #333;
          border-left: 6px solid transparent;
          border-bottom-color: transparent;
          border-right: 6px solid transparent;
        }
      }
    }
    .cell:last-child{
      border-bottom: none;
    }
  }
}
.order-compute{
  background: #FFFFFF; margin-top: 16px;
  .cell{
    display: flex;
    align-items: center;
    padding: 0 24px;
    height: 100px;
    border-bottom: 2px solid $uni-page-bg;
    ._lf-title{
      min-width: 112px;
      font-size: 30px;
      color: $uni-color-default;
      margin-right: 28px;

      .label{
        display: flex;
        align-items: center;

        .icon{
          margin-right: 16px;
        }
      }
    }
    ._rt{
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      font-size: 32px;
    }
  }
  .cell:last-child{
    border-bottom: none;
  }
}
.pay{
  border-top: 1px solid #E6E6E6;
  margin-top: 16px;
  background: #FFFFFF;
  ._btn{
    position: relative;
    margin: 0 auto;
    padding: 16px 16px 0;
    width: 702px;
  }
}

.m-service-provider{
  font-size: 22px; color: #999; padding-top: 20px; padding-bottom: env(safe-area-inset-bottom); text-align: center;
  view{
    //text-overflow: ellipsis;
    //white-space: nowrap;
    //overflow: hidden;
    line-height: 1.8; display: flex; align-items: center; justify-content: center;}
  .store-name{
    text-decoration: underline;
    //display: inline-block; max-width: 400px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;
  }
}

// sku模块内容样式
.x-product-sku {
  ._sku{
    padding: 20px;
    & + ._sku { padding-top: 0;}
    &._combo{ padding-bottom: 0;}
  }
  ._dt{ font-size: 30px; color: $uni-color-default; padding-bottom: 20px;}
  ._dd{
    display: flex; flex-wrap: wrap;
    ._li{
      min-width: 144px;  border-radius: 10px; border: 2px solid $uni-bg-color-grey; color: $uni-color-default; text-align: center; padding: 18px 16px; font-size: 28px; line-height: 28px; margin-right: 30px; margin-bottom: 30px; background: $uni-bg-color-grey;
      &.is-active{ background-color: rgba(235, 68, 31, 0.06); color: #DE3A2E;border: 2px solid #DE3A2E}
    }
  }
  ._desc{ padding-bottom: 20px; font-size: 28px; color: $uni-color-primary;}
}

.bold{
  font-weight: 600;
}

.is-template-3{
  background: #F7F7F9;
  padding: 0 var(--padding);

  .section{
    padding: 20px 24px;
    background: #FFFFFF;
    border-radius: 16px;
    & + .section{
      margin-top: 20px;
    }

    &.no-padding{
      padding: 0;
    }
    &.no-padding-left{
      padding-left: 0;
    }
    &.no-padding-right{
      padding-right: 0;
    }
  }

  ._header-top{
    background: #F7F7F9;
    padding-bottom: 16px;
    .selected-sku-box{
      display: flex;
      padding: 24px 0;border-bottom: none;
    }
  }

  .p-set-order{
    ._scroll {
      ._num {
        border-bottom: none
      }
    }
  }

  .address-box{
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 30px;
    padding: 30px 24px;
    .address-content{
      display: flex;
      .address-icon{
        width: 40px;
        height: 40px;
        flex: none;
        margin-right: 10px;
      }

      .address-detail{
        .user-info{
          display: flex;
          align-items: center;
          .user-name{
            font-weight: 600;
          }
          .user-mobile{
            margin-left: 10px;
            font-size: 28px;
            color: #6E6E6E;
          }
        }
        .address{
          color: #6E6E6E
        }
      }
    }
    .fill-tips{
      font-size: 30px;
      font-weight: 600;
    }
  }
  .remark-box{
    display: flex;
    align-items: center;
    font-size: 30px;
    padding: 0 24px 24px;
    .label{
      margin-right: 10px;
    }

    .input{
      flex: 1;
    }
  }

  .order-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28px;

    .label{
      display: flex;
      align-items: center;

      .icon{
        margin-right: 16px;
      }
    }

    .text{
      color: #6E6E6E;
    }
  }

  .btn-buy{
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26px;

    .price{
      display: flex;
      align-items: baseline;
    }

    .value{
      font-size: 44px;
    }
  }

  .pay{
    margin-top: 0;
    ._btn{
      padding-top: 6px;
    }
  }

  .order-compute{
    border-radius: 16px;
  }
  .conveniently-buy{
    margin-top: 16px;
  }
}

.charge-list{
  min-height: 55vh;
  background: #F5F5F5;
  padding-bottom: 400px;

  .charge-content{
    background: #ffffff;
    padding: 10px;
    border-radius: 30px;
    margin: 0 var(--padding);
  }
}

.mt-16{
  margin-top: 16px;
}
</style>
